import { User } from "server/models/User";
import { FileModel } from "server/models/File";
import { paginatedResponse } from "server/utils/response";

export default defineEventHandler(async (event) => {
  try {
    const query = getQuery(event);
    const page = parseInt(query.page as string) || 1;
    const pageSize = Math.min(parseInt(query.pageSize as string) || 10, 50);
    const search = query.search as string;
    const role = query.role as string;
    const status = query.status as string;
    
    try {
      const result = await User.getAllUsers(page, pageSize);

      // 应用筛选逻辑
      let filteredData = result.data;

      if (search) {
        const searchLower = search.toLowerCase();
        filteredData = filteredData.filter(
          (user) =>
            user.username.toLowerCase().includes(searchLower) ||
            user.email.toLowerCase().includes(searchLower) ||
            user.nickname?.toLowerCase().includes(searchLower)
        );
      }

      if (role) {
        filteredData = filteredData.filter((user) => user.role === role);
      }

      if (status) {
        filteredData = filteredData.filter((user) => user.status === status);
      }

      // 重新计算分页
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      const paginatedData = filteredData.slice(startIndex, endIndex);

      // 处理头像字段，转换为URL
      const processedData = await Promise.all(
        paginatedData.map(async (user) => {
          let avatarUrl = "";
          if (user.avatar && typeof user.avatar === 'number') {
            try {
              const avatarFile = await FileModel.findById(user.avatar);
              if (avatarFile) {
                avatarUrl = avatarFile.url || "";
              }
            } catch (fileError) {
              console.warn("获取头像文件失败:", fileError);
            }
          }
          
          return {
            ...user,
            avatar_url: avatarUrl,
          };
        })
      );

      return paginatedResponse(
        processedData,
        {
          page,
          pageSize,
          total: filteredData.length,
          totalPages: Math.ceil(filteredData.length / pageSize),
        },
        "获取用户列表成功"
      );
    } catch (dbError) {
      console.warn("获取用户列表失败:", dbError);
      return {
        success: false,
        error: "获取用户列表失败",
        message: dbError instanceof Error ? dbError.message : "未知错误",
      };
    }
  } catch (error) {
    console.error("获取用户列表失败:", error);
    return {
      success: false,
      error: "获取用户列表失败",
      message: error instanceof Error ? error.message : "未知错误",
    };
  }
});
